#include <stdlib.h>
#include "base/core/raw_allocator.h"
#include "base/core/mem_tracker.h"
#include "base/core/Profiler.h"

RawAllocator::RawAllocator() 
{}

RawAllocator::~RawAllocator() 
{}

void* RawAllocator::Alloc(size_t size) 
{
    return malloc(size);
}

void* RawAllocator::Realloc(void* ptr, size_t size) 
{
    return realloc(ptr, size);
}

void  RawAllocator::Free(void* ptr) 
{
    free(ptr);
}

void* RawAllocator::AllocTrack(size_t size,
                               const char* file,
                               const char* func,
                               uint32_t line)
{
    void* ret = NULL;
    BEGIN_PROFILE("RawAllocator::AllocTrack");
    BEGIN_PROFILE("Alloc");
    ret = Alloc(size);
    END_PROFILE();

    if (ret) 
	{
        BEGIN_PROFILE("Track");
        g_MemTracker().TrackMalloc(ret, file, func, line);
        END_PROFILE();
    }
    END_PROFILE();
    return ret;
}

void* RawAllocator::ReallocTrack(void* ptr,
                                 size_t size,
                                 const char* file,
                                 const char* func,
                                 uint32_t line) 
{
    if (ptr == NULL) 
	{
        return AllocTrack(size, file, func, line);
    }
    void* ret = realloc(ptr, size);
    if (ret != NULL && ret != ptr) 
	{
        g_MemTracker().TrackFree(ptr);
        g_MemTracker().TrackMalloc(ret, file, func, line);
    }
    return ret;
}

void RawAllocator::FreeTrack(void* ptr) 
{
	assert(ptr != NULL);
	g_MemTracker().TrackFree(ptr);
	free(ptr);
}
